package com.hepinghospital.user.ui.activity.eyecheck;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.adapter.EyeYaDetailAdapter;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.ui.activity.home.BookDoctor2Activity;
import com.hepinghospital.user.ui.dialog.ApplyPermissionDialog;
import com.hepinghospital.user.ui.dialog.SelectPicModeDialog;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.PermissionsChecker;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.constant.JDConstant;
import com.rest.observer.BaseObserver;
import com.rest.response.BaseJsonResponse;
import com.rest.response.PicUploadResponse;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.UriUtils;
import jz.joyoung.robot.util.UtilList;
import jz.joyoung.robot.util.UtilString;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 眼压 详情
 *
 * @time 2021/1/6 10:50
 */

public class EyeYaDetailActivity extends BaseActivity {


    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.btn_add_family)
    TextView btnAddFamily;
    @BindView(R.id.tv_eye_type)
    TextView tvEyeType;
    @BindView(R.id.tv_patient_name)
    TextView tvPatientName;
    @BindView(R.id.tv_eye_left)
    TextView tvEyeLeft;
    @BindView(R.id.tv_look_time)
    TextView tvLookTime;
    @BindView(R.id.tv_eye_hospital_name)
    TextView tvEyeHospitalName;
    @BindView(R.id.rv_eye_ya)
    RecyclerView rvEyeYa;
    @BindView(R.id.ll_eye_add)
    LinearLayout llEyeAdd;
    @BindView(R.id.tv_save_eye)
    TextView tvSaveEye;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    List<BaseJsonResponse.Impression> mEyeYaList = new ArrayList<>();
    List<BaseJsonResponse.Impression> mEyeYaListAverage = new ArrayList<>();
    @BindView(R.id.et_eye_ya_left)
    EditText etEyeYaLeft;
    @BindView(R.id.tv_eye_ya_left)
    TextView tvEyeYaLeft;
    @BindView(R.id.et_eye_ya_right)
    EditText etEyeYaRight;
    @BindView(R.id.tv_eye_ya_right)
    TextView tvEyeYaRight;
    @BindView(R.id.iv_eye_ya_minio)
    ImageView ivEyeYaMinio;
    @BindView(R.id.tv_eye_ya_minio)
    TextView tvEyeYaMinio;
    private EyeYaDetailAdapter eyeYaDetailAdapter;
    private SelectPicModeDialog mSelectPicModeDialog = null;
    //原图像 URI
    public Uri imgUriOri;
    //原图像 路径
    public static String imgPathOri, resourceId;
    String checkDetailId, checkFlag, url;
    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
    };
    private PermissionsChecker mPermissionsChecker; // 权限检测器

    @Override
    protected void initViews() {

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rvEyeYa.setLayoutManager(manager);
        eyeYaDetailAdapter = new EyeYaDetailAdapter(mContext, mEyeYaList);
        rvEyeYa.setAdapter(eyeYaDetailAdapter);
        etEyeYaLeft.addTextChangedListener(new Watcher(etEyeYaLeft, "0"));
        etEyeYaRight.addTextChangedListener(new Watcher(etEyeYaRight, "1"));
    }

    @Override
    protected void initData() {
        checkDetailId = getIntent().getStringExtra("checkDetailId");
        queryCheckDetail();
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_eye_ya_detail;
    }


    private void queryCheckDetail() {
        RestProxy.getInstance().queryCheckDetail(checkDetailId, new Observer<BaseJsonResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onNext(BaseJsonResponse baseJsonResponse) {
                try {
                    tvTitle.setText(baseJsonResponse.checkItem + "详情");
                    tvEyeType.setText(baseJsonResponse.checkItem);
                    tvPatientName.setText(baseJsonResponse.patientName);
                    tvEyeHospitalName.setText(baseJsonResponse.hosName);
                    tvLookTime.setText(baseJsonResponse.checkTime);
                    tvEyeLeft.setText(baseJsonResponse.checkSeries);
                    checkFlag = baseJsonResponse.checkFlag;
                    url = baseJsonResponse.url;

                    if (!"2".equals(checkFlag)) {
                        //可以编辑
                        ivEyeYaMinio.setVisibility(View.VISIBLE);
                        tvEyeYaMinio.setVisibility(View.VISIBLE);
                        ivEyeYaMinio.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.icon_eye_error));
//                        if (baseJsonResponse.data.url != null) {
//                            ImageLoaderHelper.getInstance().GlideImageLoader( mContext, url, ivEyeYaMinio );
//                        } else {
//                            ivEyeYaMinio.setImageDrawable( ContextCompat.getDrawable( mContext, R.mipmap.icon_eye_error ) );
//                        }
                    } else {
                        if (!UtilString.isEmpty(url)) {
                            ImageLoaderHelper.getInstance().GlideImageLoader(mContext, url, ivEyeYaMinio);
                        } else {
                            ivEyeYaMinio.setVisibility(View.GONE);
                            tvEyeYaMinio.setVisibility(View.GONE);
                        }

                    }
                    List<BaseJsonResponse.Impression> impressionList = baseJsonResponse.impression;
                    if (!UtilList.isEmpty(impressionList)) {
                        Log.e("眼压集合---", impressionList.size() + "");
                        mEyeYaList.clear();
                        if (impressionList.size() > 1) {
                            for (int i = 0; i < impressionList.size() - 1; i++) {
                                mEyeYaList.add(impressionList.get(i));
                            }
                            etEyeYaLeft.setVisibility(View.GONE);
                            etEyeYaRight.setVisibility(View.GONE);
                            tvEyeYaLeft.setVisibility(View.VISIBLE);
                            tvEyeYaRight.setVisibility(View.VISIBLE);
                            tvEyeYaLeft.setText(impressionList.get(impressionList.size() - 1).osEyePressure);
                            tvEyeYaRight.setText(impressionList.get(impressionList.size() - 1).odEyePressure);
                        } else {
                            mEyeYaList.addAll(baseJsonResponse.impression);
                        }
                        eyeYaDetailAdapter.setCheckFlag(checkFlag);
                        eyeYaDetailAdapter.notifyDataSetChanged();
                        //有数据不能添加次数和编辑
                        llEyeAdd.setVisibility(View.GONE);
                        tvSaveEye.setVisibility(View.GONE);
                    } else {
                        etEyeYaLeft.setVisibility(View.VISIBLE);
                        etEyeYaRight.setVisibility(View.VISIBLE);
                        tvEyeYaLeft.setVisibility(View.GONE);
                        tvEyeYaRight.setVisibility(View.GONE);
                        BaseJsonResponse.Impression impression = new BaseJsonResponse.Impression();
                        impression.osEyePressure = "";
                        impression.odEyePressure = "";
                        mEyeYaList.add(impression);
                        //新增一条平均值
                        BaseJsonResponse.Impression impressionTwo = new BaseJsonResponse.Impression();
                        impressionTwo.osEyePressure = "";
                        impressionTwo.odEyePressure = "";
                        impressionTwo.title = "眼压测量结果（平均数值)";
                        mEyeYaListAverage.add(impressionTwo);
                        eyeYaDetailAdapter.setCheckFlag("1");
                        eyeYaDetailAdapter.notifyDataSetChanged();
                    }

                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(EyeYaDetailActivity.this, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }


    @OnClick({R.id.tv_save_eye, R.id.tv_submit, R.id.ll_eye_add, R.id.iv_eye_ya_minio})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_save_eye:
                editCheckDetail();
                break;
            case R.id.tv_submit:
                Bundle bundleOne = new Bundle();
                bundleOne.putInt("type", 1);
                bundleOne.putString("checkDetailId", checkDetailId);
                startActivity(BookDoctor2Activity.class, bundleOne);
                break;
            case R.id.ll_eye_add:
                mEyeYaList.add(new BaseJsonResponse.Impression());
                eyeYaDetailAdapter.notifyDataSetChanged();
                break;
            case R.id.iv_eye_ya_minio:
                if (!"2".equals( checkFlag )) {
                    // 缺少权限时, 进入权限配置页面
                    if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                        getPermission();
                    }else {
                        showSelectHeadPicDialog();
                    }
                } else {
                    if (!UtilString.isEmpty(url)) {
                        Bundle bundle = new Bundle();
                        bundle.putString("url", url);
                        bundle.putInt("type", 1);
                        startActivity(BigImageActivity.class, bundle);
                    }

                }
                break;
        }
    }

    private void editCheckDetail() {
//        eyeYaDetailAdapter.notifyDataSetChanged();
        mEyeYaList.addAll(mEyeYaListAverage);
        Log.e("editCheckDetail----", mEyeYaList.get(0).odEyePressure);
        RestProxy.getInstance().editCheckDetail(checkDetailId, mEyeYaList, new Observer<BaseJsonResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseJsonResponse baseResponse) {
                try {
                    ToastUtil.showToast(mContext, "保存成功");
                    finish();
                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(EyeYaDetailActivity.this, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void showSelectHeadPicDialog() {
        if (mSelectPicModeDialog == null) {
            // 初始化点击头像弹出的对话框
            mSelectPicModeDialog = SelectPicModeDialog.newInstance();
            mSelectPicModeDialog.setOnItemClickListener(new SelectPicModeDialog.OnItemClickListener() {
                @Override
                public void takePhotoClick() {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File oriPhotoFile = null;
                    try {
                        oriPhotoFile = createOriImageFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                        imgUriOri = Uri.fromFile(oriPhotoFile);
                    } else {
                        imgUriOri = FileProvider.getUriForFile(mContext, UIConstants.FILE_PROVIDER_URI, oriPhotoFile);
                    }
//                    phoneCamearUri = FileProvider.getUriForFile(PersonInfoActivity.this,"com.joyoung.robot.phone.provider",file);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUriOri);
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    startActivityForResult(intent, UIConstants.REQUEST_OPEN_CAMERA);
                }

                @Override
                public void pickFromAlbumClick() {
                    Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(intent, UIConstants.REQUEST_GALLERY);
                }
            });
        }
        mSelectPicModeDialog.show(getSupportFragmentManager(), "SelectPicModeDialog");


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        //data的返回值根据
        switch (requestCode) {

            case UIConstants.REQUEST_OPEN_CAMERA:
                getPresignedUrl(imgPathOri);
//                uploadFile( imgPathOri );
                break;
            case UIConstants.REQUEST_GALLERY:
                Log.e("相册头像---", data.toString());
                Uri imgUriSel = data.getData();
                String imgPathSel = UriUtils.formatUri(this, imgUriSel);
                getPresignedUrl(imgPathSel);
//                    uploadFile( imgPathSel );

                break;


            default:
                break;
        }
    }


    /**
     * 获取minio服务器域名
     *
     * @time 2020/12/2 10:21
     */
    private void getPresignedUrl(String imgPathSel) {
        showLoadingDialog(this);
        // bucket:   1-病历 2-评论(反馈) 3-头像 4-轮播图 9-聊天图片 ',
        RestProxy.getInstance().getPresignedUrl("1", new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(String baseStringResponse) {
                try {
                    String data = baseStringResponse;
                    if (data.contains("?")) {
                        String substring = data.substring(0, data.indexOf("?"));
                        resourceId = substring.substring(substring.lastIndexOf("/") + 1);
                        Log.e("presignedUrl -----", resourceId);
                        uploadFileMinio(imgPathSel,baseStringResponse);
                    }

                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }
            }

            @Override
            public void onError(Throwable e) {
                dismissLoadingDialog();
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 上传图片到minio服务器
     * <p>
     * * @time 2020/12/3 15:36
     */
    private void uploadFileMinio(String imgPath,String url) {
        new Thread(() -> {
            try {
                Log.e("TAG-路径-----", imgPath);
                File file = new File(imgPath);
                FileInputStream fileInputStream = new FileInputStream(file);
                int available = fileInputStream.available(); //返回与之关联的文件的字节数
                Log.e("字节数---", available + "");
                OkHttpClient httpClient = new OkHttpClient();
                MediaType mediaType = MediaType.parse("image/png");//设置类型
                RequestBody requestBody = RequestBody.create(mediaType, file);//把文件与类型放入请求体
                Request request = new Request.Builder()
                        .url(url)
                        .put(requestBody)
                        .build(); //创建OkHttpClient对象
                Call call = httpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("TAG-失败：", e.toString() + "");
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String string = response.body().toString();
                        Log.e("minio成功---", string + "");
                        uploadFileTb(imgPath, available + "");
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();


    }

    /**
     * 上传照片到服务器数据库
     *
     * @time 2020/12/2 9:55
     */
    private void uploadFileTb(String imgPathSel, String available) {
        // bucket:   1-病历 2-评论(反馈) 3-头像 4-轮播图 9-聊天图片 ',  默认 1 就好了 头像为3
        //relationId 检查检验图片为checkDetailId
        // type: 图片类型  患者上传默认为15  头像为30 检查图片为：14-眼压检查 15-视力检查 16-屈光检查
        RestProxy.getInstance().uploadFileTb("1", "14", resourceId, checkDetailId, available, "0", new BaseObserver<PicUploadResponse>() {

            @Override
            public void onError(Throwable e) {
                dismissLoadingDialog();
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onSuccess(PicUploadResponse picUploadResponse) {
                try {
                    runOnUiThread(() -> {
                        dismissLoadingDialog();
                        if (!UtilString.isEmpty(picUploadResponse.shareUrl)) {
                            ImageLoaderHelper.getInstance().GlideCircleImageLoader(mContext, picUploadResponse.shareUrl, ivEyeYaMinio);
                        }
                    });

                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }
            }
        });
    }


    /**
     * 创建原图像保存的文件
     *
     * @return
     * @throws IOException
     */
    protected File createOriImageFile() throws IOException {
        String imgNameOri = "HomePic_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File pictureDirOri = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/OriPicture");
        if (!pictureDirOri.exists()) {
            pictureDirOri.mkdirs();
        }
        File image = File.createTempFile(
                imgNameOri,         /* prefix */
                ".jpg",             /* suffix */
                pictureDirOri       /* directory */
        );
        imgPathOri = image.getAbsolutePath();
        return image;
    }

    @SuppressLint("CheckResult")
    private void getPermission() {
        ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance( "3", true );
        applyPermissionDialog.show( getSupportFragmentManager(), "applyPermissionDialog" );
        applyPermissionDialog.setmListener( new ApplyPermissionDialog.OnItemClickListener() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onConfirm() {
                RxPermissions permissions = new RxPermissions( EyeYaDetailActivity.this );
                permissions.request( Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE )
                        .subscribe( granted -> {
                            if (granted) {
                                //已经打开权限
                                showSelectHeadPicDialog();
                            } else {
                                ToastUtil.showToast( mContext, "请同意相册和存储权限，否则功能无法使用" );
                                startNotificationSetting(mContext);
                            }
                        } );
            }

            @Override
            public void onCancel() {

            }
        } );

    }

    class Watcher implements TextWatcher {

        EditText etTextView;
        String position, type;
        double start, end;

        Watcher(EditText editText, String position) {
            this.etTextView = editText;
            this.position = position;

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            String trim = etTextView.getText().toString().trim();
            if ("0".equals(position)) {
                //左眼
                mEyeYaListAverage.get(0).osEyePressure = trim;
            } else {
                mEyeYaListAverage.get(0).odEyePressure = trim;
            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {


        }


    }

}
